package cn.iocoder.yudao.module.call.framework.security.core.filter;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * Token 过滤器，验证 token 的有效性
 * 验证通过后，获得 {@link LoginUser} 信息，并加入到 Spring Security 上下文
 *
 * @author 芋道源码
 */
@RequiredArgsConstructor
@Slf4j
@Component
public class CallModuleTokenAuthenticationFilter extends OncePerRequestFilter {

//    @Resource
//    private ServiceCustomerService serviceCustomerService;

    private static final String IDF = "call";

    @Override
    @SuppressWarnings("NullableProblems")
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        String scene = request.getParameter("scene");
        String clientType = request.getParameter("clientType");
        String tenantIdStr = TenantContextHolder.getTenantIdStr();
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        if (Objects.isNull(loginUserId)) {
            return;
        }
        if (!Objects.equals(IDF, scene)) {
            chain.doFilter(request, response);
        } else {
            if (StrUtil.isEmpty(clientType)) {
                log.error("Client Type Empty");
                return;
            }
            // Server 是管理端， Client 是移动端
            if (Objects.equals(clientType, "Server")) {
                // 管理员使用token验证，直接放过
                chain.doFilter(request, response);
            } else if (Objects.equals(clientType, "Client")) {
                String id = StrUtil.concat(true, "97", StrUtil.fillBefore(String.valueOf(loginUserId), '0', 10));
                LoginUser loginUser = new LoginUser();
                loginUser.setId(Long.parseLong(id));
                loginUser.setUserType(UserTypeEnum.ADMIN.getValue());
                SecurityFrameworkUtils.setLoginUser(loginUser, request);
            } else {
                log.error("Client Type Not Found");
            }
            chain.doFilter(request, response);
        }


    }

//    private LoginUser buildUserFromCustomer(ServiceCustomerDO customer) {
//        LoginUser loginUser = new LoginUser();
//        loginUser.setId(customer.getLoginUserId());
//        loginUser.setUserType(UserTypeEnum.MEMBER.getValue());
//        loginUser.setTenantId(customer.getTenantId());
//        loginUser.setSessionId(customer.getSessionId());
//        return loginUser;
//    }


    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        return !StrUtil.equals(request.getRequestURI(), "/infra/ws");
    }
}
